<template>
  <div>
    <!-- 批量删除确认对话框 -->
    <el-dialog :title="title" v-model="dialogVisible" width="30%">
      <span>确认要删除选中的 {{ selectedItems.length }} 条数据吗?</span>

      <!-- 删除进度条 -->
      <BatchOperationProgress
        :visible="showProgress"
        :current="progress.current"
        :total="progress.total"
        :success="progress.success"
        :failed="progress.failed"
        title="删除进度"
        :operation-text="`正在删除第 ${progress.current} 条数据...`"
        completed-text="删除完成！"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" :disabled="deleting">取 消</el-button>
          <el-button type="primary" @click="handleBatchDelete" :loading="deleting" :disabled="deleting">
            {{ deleting ? '删除中...' : '确定删除' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import http from "@/utils/request";
import BatchOperationProgress from './BatchOperationProgress.vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  selectedItems: {
    type: Array,
    default: () => []
  },
  deleteUrl: {
    type: String,
    default: ''
  },
  idField: {
    type: String,
    default: 'id'
  },
  title: {
    type: String,
    default: '批量删除确认'
  }
});

const emit = defineEmits(['update:visible', 'delete-success', 'delete-complete']);

const dialogVisible = ref(false);
const deleting = ref(false);
const showProgress = ref(false);
const progress = reactive({
  current: 0,
  total: 0,
  percentage: 0,
  success: 0,
  failed: 0
});

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
});

// 监听dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val);
  // 关闭对话框时重置状态
  if (!val) {
    resetProgress();
  }
});

// 重置进度状态
const resetProgress = () => {
  progress.current = 0;
  progress.total = 0;
  progress.percentage = 0;
  progress.success = 0;
  progress.failed = 0;
  showProgress.value = false;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
};

// 执行批量删除
const handleBatchDelete = async () => {
  if (props.selectedItems.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }

  if (!props.deleteUrl) {
    ElMessage.error('未指定删除接口');
    return;
  }

  deleting.value = true;

  // 重置进度状态
  resetProgress();
  progress.total = props.selectedItems.length;
  showProgress.value = true;

  try {
    // 逐个删除选中的项目并更新进度
    for (let i = 0; i < props.selectedItems.length; i++) {
      progress.current = i + 1;

      try {
        const response = await http.post(props.deleteUrl, { [props.idField]: props.selectedItems[i][props.idField] });
        if (response.code === 200) {
          progress.success++;
        } else {
          progress.failed++;
          console.error(`删除数据失败：${response.msg}`);
        }
      } catch (error) {
        progress.failed++;
        console.error('删除数据时出错:', error);
      }
    }

    // 删除完成后的提示和操作
    if (progress.success > 0) {
      ElMessage.success(`删除完成：成功${progress.success}个，失败${progress.failed}个`);

      // 通知父组件删除成功，可以刷新数据
      emit('delete-success', {
        success: progress.success,
        failed: progress.failed,
        total: progress.total
      });

      // 延迟关闭对话框，让用户看到最终进度
      setTimeout(() => {
        dialogVisible.value = false;
        emit('delete-complete');
      }, 300);
    } else {
      ElMessage.error('删除失败：没有成功删除的数据');
    }
  } catch (error) {
    console.error('批量删除过程中出错:', error);
    ElMessage.error('批量删除过程中出错');
  } finally {
    deleting.value = false;
  }
};
</script>

<style scoped>
/* 按需添加样式 */
</style>
